package cn.wolfcode.web.modules.linkman.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.wolfcode.web.commons.entity.LayuiPage;
import cn.wolfcode.web.commons.utils.LayuiTools;
import cn.wolfcode.web.commons.utils.PoiExportHelper;
import cn.wolfcode.web.commons.utils.SystemCheckUtils;
import cn.wolfcode.web.modules.BaseController;
import cn.wolfcode.web.modules.cust.entity.TbCustomer;
import cn.wolfcode.web.modules.cust.service.ITbCustomerService;
import cn.wolfcode.web.modules.log.LogModules;
import cn.wolfcode.web.modules.sys.entity.SysUser;
import cn.wolfcode.web.modules.sys.form.LoginForm;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


import cn.wolfcode.web.modules.linkman.entity.TbCustLinkman;
import cn.wolfcode.web.modules.linkman.service.ITbCustLinkmanService;


import link.ahsj.core.annotations.AddGroup;
import link.ahsj.core.annotations.SameUrlData;
import link.ahsj.core.annotations.SysLog;
import link.ahsj.core.annotations.UpdateGroup;
import link.ahsj.core.entitys.ApiModel;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 陈天狼
 * @since 2023-09-21
 */
@Controller
@RequestMapping("linkmaninfo")
public class TbCustLinkmanController extends BaseController {

    @Autowired
    private ITbCustLinkmanService entityService;

    @Autowired
    private ITbCustomerService customerService;

    private static final String LogModule = "TbCustLinkman";

    @GetMapping("/list.html")
    public ModelAndView list(ModelAndView mv) {
        List<TbCustomer> list=customerService.list();
       mv.addObject("custs",list);
        mv.setViewName("linkman/linkmaninfo/list");
        return mv;
//        return "linkman/linkmaninfo/list";
    }

    @RequestMapping("/add.html")
    @PreAuthorize("hasAuthority('linkman:linkmaninfo:add')")
    public ModelAndView toAdd(ModelAndView mv) {
        List<TbCustomer> list=customerService.list();
        mv.addObject("custs", list);
        mv.setViewName("linkman/linkmaninfo/add");
        return mv;
    }

    @GetMapping("/{id}.html")
    @PreAuthorize("hasAuthority('linkman:linkmaninfo:update')")
    public ModelAndView toUpdate(@PathVariable("id") String id, ModelAndView mv) {
        List<TbCustomer> list=customerService.list();
        mv.addObject("custs", list);

        mv.setViewName("linkman/linkmaninfo/update");
        mv.addObject("obj", entityService.getById(id));
        mv.addObject("id", id);
        return mv;
    }

    @RequestMapping("list")
    @PreAuthorize("hasAuthority('linkman:linkmaninfo:list')")
    public ResponseEntity page(LayuiPage layuiPage,String parameterName,String custId) {
        SystemCheckUtils.getInstance().checkMaxPage(layuiPage);
        IPage page = new Page<>(layuiPage.getPage(), layuiPage.getLimit());

        page=entityService.lambdaQuery()
                .eq(!StringUtils.isEmpty(custId),TbCustLinkman::getCustId,custId)
                .like(!StringUtils.isEmpty(parameterName),TbCustLinkman::getLinkman,parameterName)
                .or()
                .like(!StringUtils.isEmpty(parameterName),TbCustLinkman::getPhone,parameterName)
                .page(page);
        return ResponseEntity.ok(LayuiTools.toLayuiTableModel(page));
    }

    @SameUrlData
    @PostMapping("save")
    @SysLog(value = LogModules.SAVE, module =LogModule)
    @PreAuthorize("hasAuthority('linkman:linkmaninfo:add')")
    public ResponseEntity<ApiModel> save(@Validated({AddGroup.class}) @RequestBody TbCustLinkman entity,HttpServletRequest request) {
        entity.setInputTime(LocalDateTime.now());
        SysUser loginUse=(SysUser)request.getSession().getAttribute(LoginForm.LOGIN_USER_KEY);
        entity.setInputUser(loginUse.getUserId());

        entityService.save(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SameUrlData
    @SysLog(value = LogModules.UPDATE, module = LogModule)
    @PutMapping("update")
    @PreAuthorize("hasAuthority('linkman:linkmaninfo:update')")
    public ResponseEntity<ApiModel> update(@Validated({UpdateGroup.class}) @RequestBody TbCustLinkman entity) {
        entityService.updateById(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SysLog(value = LogModules.DELETE, module = LogModule)
    @DeleteMapping("delete/{id}")
    @PreAuthorize("hasAuthority('linkman:linkmaninfo:delete')")
    public ResponseEntity<ApiModel> delete(@PathVariable("id") String id) {
        entityService.removeById(id);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SysLog(value = LogModules.DELETE, module = LogModule)
    @RequestMapping("export")
    public void export(HttpServletResponse response, String parameterName, String custId){
        System.out.println("导出的参数1"+ parameterName);
        System.out.println("导出的参数1"+ custId);

        List<TbCustLinkman> list=entityService.lambdaQuery()
                .eq(!StringUtils.isEmpty(custId),TbCustLinkman::getCustId,custId)
                .like(!StringUtils.isEmpty(parameterName),TbCustLinkman::getLinkman,parameterName)
                .or()
                .like(!StringUtils.isEmpty(parameterName),TbCustLinkman::getPhone,parameterName)
                .list();
        ExportParams exportParams =new ExportParams();
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams,TbCustLinkman.class,list);

        try {
            PoiExportHelper.exportExcel(response,"联系人管理",workbook);
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
    }
}
